import config from '../config/index.js'
import utils from '../utils/util.js'
const app = getApp();

let lock = false;
let job = [];

const _login = (cb) => {
  // return new Promise((resolve, reject) => {
  let code = '';
  wx.pro.login().then(res => {
    code = res.code;
    return wx.pro.getSetting()
  }).then(res => {
    console.log('获取用户配置', res);
    if (res.authSetting['scope.userInfo']) {
      return wx.pro.getUserInfo()
    }
  }).then(res => {
    console.log('获取用户信息', res);
    return postRequest('/m/api/wx_login', {
      code: code,
      iv: res.iv,
      encryptedData: res.encryptedData,
      userinfo: JSON.stringify(res.userInfo)
    })
  }).then(res => {
    console.log('res', res)
    let token = res.data.token;
    let userInfo = res.data.userinfo

    console.log('token', token);
    wx.setStorageSync('t', token)
    wx.setStorageSync('userInfo', userInfo)
    console.log('登陆成功', userInfo)
    app.globalData.userInfo = userInfo;
    cb && cb(res);
  }).catch(error => {
    console.log(error)
  })
}

function wxPromisefy(obj = {}) {
  return new Promise((resolve, reject) => {
    obj.header = obj.header ? obj.header : {}
    obj.header = Object.assign(obj.header, {
      'token': wx.getStorageSync('t')
    })
    obj.success = function(res) {
      console.log('success res: ', res);
      // 未登录或token 过期， 重新调用登陆接口 
      if (res.data.code == 3) {
        console.log('未登录')
        job.push({
          url: obj.url,
          method: obj.method,
          header: utils.deepClone(obj.header),
          data: JSON.parse(JSON.stringify(obj.data || {})),
          success: obj.success,
          fail: obj.fail,
        });

        if (!lock) {
          lock = true;
          _login(data => {
            lock = false;
            console.log('job', job);
            for (let i = 0; i < job.length; i++) {
              console.log('重新发送请求', job[i])
              job[i].header.token = data.data.token;
              wx.request({
                ...job[i]
              });
            };
            job = [];
          })
        }
        return;
      }
      resolve(res.data)
    }
    wx.request(obj);
  })
}

function postRequest(url, data = {}, header = {}) {
  return wxPromisefy({
    url: config.domain + url,
    method: 'POST',
    data: data,
  })
}

function getRequest(url, data = {}, header = {}) {
  return wxPromisefy({
    url: config.domain + url,
    method: 'POST',
    data: data
  })
}


module.exports = {
  postRequest: postRequest,
  getRequest: getRequest
}